package com.haozi.watchtomato.util;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 时间工具类
 *
 * @author junsi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYYMMDDHHMMSS_SSS = "yyyyMMddHHmmssSSS";

    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYYMM = "yyyyMM";

    public static String YYYYMMDD_1 = "yyyy/MM/dd";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
	{
		LocalDateTime ldt = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
		return ldt.format(dtf);
	}

	public static final Date dateTime(final String format, final String ts) {
		DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern(format + "[['T'HH][:mm][:ss]]")
				.parseDefaulting(ChronoField.HOUR_OF_DAY, 0).parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
				.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0).parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
				.toFormatter();
		LocalDateTime localDateTime = LocalDateTime.parse(ts, dtf);
		return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
	}

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime(String dateString){
        try{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = format.parse(dateString);
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = outputFormat.format(date);
            return formattedDate;
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * @Des 获取本年尚余月份数
     **/
     public static Integer getSurplusMonthNum(){
    	 LocalDate localDate = LocalDate.now();
         int month = localDate.getMonthValue();
         return 12 - month;
     }

    /**
     * @Des 获取本年尚余月份数
     **/
    public static Integer getYear(int i){
    	LocalDate localDate = LocalDate.now();
        Integer year = localDate.getYear() + i;
        return year;
    }

    /**
     * 获取Date类型转化成字符串格式不带时分秒
     * @return
     */
    public static String formateToString(Date date){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = formatter.format(date);
        return time;

    }

	/**
	 * 转换为时间（天,时:分:秒.毫秒）
	 * @param timeMillis
	 * @return
	 */
	public static String formatDateTime(long timeMillis) {
		long day = timeMillis / (24 * 60 * 60 * 1000);
		long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
		long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
		long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
		return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss;
	}

	public static Date zoneToLocalTime(String dateString) {
		DateTimeFormatter simpleDateFormat = DateTimeFormatter.ofPattern("yyyy-M-d'T'HH:mm:ss.SSS'Z'");
		System.out.println(dateString);
		LocalDateTime localDateTime = LocalDateTime.parse(dateString, simpleDateFormat);
		localDateTime = localDateTime.plusHours(8);

		Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
		return date;
	}

	public static String getLocalCnDateStr(String cstDateStr, String format) {
		if (format == null) {
			format = "yyyy-MM-dd HH:mm:ss";
		}
		DateTimeFormatter sdf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
		LocalDateTime localDateTime = LocalDateTime.parse(cstDateStr, sdf);
		return localDateTime.format(DateTimeFormatter.ofPattern(format, Locale.US));
	}

    /**
     * 日减7，然后月减1
     * @param dateStr yyyyMMdd
     * @return
     */
	public static String getMonthTimest(String dateStr) {
		LocalDate parse = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("yyyyMMdd"));
		parse = parse.minusDays(7);
		parse = parse.minusMonths(1);
		return parse.format(DateTimeFormatter.ofPattern(DateUtils.YYYYMM));
	}

	/**
	 * 指定月份增加月数
	 * @param dateStr yyyyMM
	 * @return
	 */
	public static String getLastMonthTimest(String dateStr, int num) {
		int year = Integer.parseInt(dateStr.substring(0, 4));
		int month = Integer.parseInt(dateStr.substring(4, 6));
		LocalDate parse = LocalDate.of(year, month, 1);
		parse = parse.plusMonths(num);
		return parse.format(DateTimeFormatter.ofPattern(DateUtils.YYYYMM));
	}
	/**
	 *
	 * getWeekStartDate:(获取上周的第一天). <br/>
	 *
	 * @author 86132
	 * @return
	 * @since JDK 1.6
	 */
	public static String getWeekStartDate(){
	    Calendar cal = Calendar.getInstance();
	    cal.add(Calendar.DATE, -1*7);
	    cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
	    Date date = cal.getTime();
	    SimpleDateFormat formatter = new SimpleDateFormat(YYYYMMDD);
	    String dateString = formatter.format(date);
	    return dateString;
	}

	/**
     *
     * get2WeeksAgoStartDate:(获取上上周的第一天). <br/>
     *
     * @author 86132
     * @return
     * @since JDK 1.6
     */
    public static String get2WeeksAgoStartDate(){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -2*7);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        Date date = cal.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat(YYYYMMDD);
        String dateString = formatter.format(date);
        return dateString;
    }

    public static Date getCurrentDate() throws ParseException {
        String dateStr = DateUtils.formateToString(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(dateStr);
        return date;
    }

    public static void main(String[] args) throws ParseException {
//    	String num="Mon Apr 17 09:10:15 CST 2017";
//		String date = getLocalCnDateStr(num,"yyyy-MM-dd HH:mm:ss");
//		System.out.println(date);
//    	Date date1 = zoneToLocalTime("2020-5-26T03:16:03.944Z");
//    	System.out.println(date1);
//    	int  day = getYear(1);
//    	System.out.println(day);
//    	int  mon = getSurplusMonthNum();
//    	System.out.println(mon);
//    	String dates = getMonthTimest("20200628");
//    	System.out.println(dates);
//    	String lastMon = getLastMonthTimest("20201226",1);
//    	System.out.println(lastMon);
    	//String getWeekStartDate = getWeekStartDate();
        //String get2WeeksAgoStartDate = get2WeeksAgoStartDate();
        //System.out.println(getWeekStartDate);
        //System.out.println(get2WeeksAgoStartDate);
        System.out.println(dateTime("2024-01-08 15:34:38.435682"));
    }


}
